%function inspection_game_bcoe(alpha,lambda,bonus,ntrials)
%initialize all variables
clear
if 1 
    clear
    alpha=.2 % .1 to .9
    lambda=.1 % set to .1 
    bonus=.1
end
pshirk=0.5;% likelyhood employee will shirk (assume no knowldge at first)
pshirkadj=0.5; %adjusted likelyhood employee will shirk (assume no knowldge at first)
pinspect=0.5;% likelyhood corp will inspect (assume no knowldge at first)
pinspectadj=0.5; %adjusted likelyhood corp will inspect (assume no knowldge at first)
corpcash=0;%money values
empcash=0;%money values
prevwork=1;%variable to check if work/shirk is repeated (think of the interview as work)
previnspect=1;%variable to check if inspect is repeated (think of the interview as inspect)

repwindow=20; %how far back to check for local repetition
rep_cnt_emp=uint8(zeros(1,repwindow));
rep_act_emp=0.5;% actual repetition rate for employee
rep_exp_emp=0.5;% corporation's expected repetition rate for employee eq(8)

rep_cnt_corp=uint8(zeros(1,repwindow));
rep_act_corp=0.5;% actual repetition rate for corporation
rep_exp_corp=0.5;% employee's expected repetition rate for corporation eq(8)

prod_gain= 3; % production gain. everything else must be smaller
wage     = 1; % wage earned 
effort   =.5; % cost or effort of labor
coi      =.5; % cost of inspection

corpgain(1,1)=prod_gain-wage-coi;
corpgain(1,2)=prod_gain-wage;
corpgain(2,1)=-coi;
corpgain(2,2)=-wage;
% corpgain=corpgain+1;

% SDinspect_a=((1-(0:.01:1))*corpgain(1,1) + (0:.01:1)*corpgain(2,1))+(.01-min(corpgain(:)));%inspect
% SDignore_a =((1-(0:.01:1))*corpgain(1,2) + (0:.01:1)*corpgain(2,2))+(.01-min(corpgain(:)));%ignore
% SDratio_corp_a=(SDinspect_a-SDignore_a)./(SDinspect_a+SDignore_a)   
% fig(213);clf;plot(SDratio_corp_a,(0:.01:1));axis([-1 1 0 1 ])
% mean(SDratio_corp_a)


empgain(1,1)=wage-effort;
empgain(1,2)=wage-effort;
empgain(2,1)=0;
empgain(2,2)=wage;


table_const=.5;
decisionlookuptable=(-100:100)';
in_range=decisionlookuptable<=(table_const*100)&decisionlookuptable>-(table_const*100);
decisionlookuptable(in_range,2)=100/sum(in_range);clear in_range
decisionlookuptable(:,2)=cumsum(decisionlookuptable(:,2));

result(2,2)=0;

prob_inspect=0.5;%random first inspection
prob_work=.5; % you gotta show up the first day...please
%prob_inspect=1;%in real world on first day there is always inspection
ntrials=500;
%fake_human=round(rand(1,ntrials));
fake_human=0;
%fake_human(1:2:200)=1;
%fake_human=[];

for t=1:ntrials
    inspect(t)=rand<=prob_inspect(t);%    inspect(t)  
    
    if isempty(fake_human)
        button = questdlg('work or shirk','work or shirk','work','shirk','work') ;
        if isempty(button)
            disp('canceled by user')
            return
        end
    else
        if length(fake_human)==ntrials
            if fake_human(t)==1
                button='work';    
            else
                button='shirk';
            end
        else
            if rand<=prob_work(t);%    work  
                button='work';    
            else
                button='shirk';
            end
        end
    end    
    %% trial done
    % t = last trial; 
    % t+1 = next trial
    
    
    if inspect(t)==1 % inspection
        if strcmp(button,'work')
            work(t)=1; 
            d_text=(upper('    keep up the good work.'));
        else % shirk
            work(t)=0; 
            d_text=(upper('    i caught you!'));
        end
        
        if prevwork==work(t)
            rep_cnt_emp(mod(t,20)+1)=1;%update rep_cnt_emp if choice was repeated
        else
            rep_cnt_emp(mod(t,20)+1)=0;%update rep_cnt_emp if choice was repeated
        end        
        rep_act_emp(t)=sum(rep_cnt_emp)/min([t, repwindow]); %this trials actual repetition score;      
        
        pshirk(t+1)=pshirk(t)+alpha*(~work(t)-pshirk(t));                  %use equation 7           
        if pshirk(t+1)>1 | pshirk(t+1)<0
            pshirk(t+1)=round(pshirk(t+1)); % must be between 0 and 1
        end
        rep_exp_emp(t+1)=pshirk(t+1)^2+(1-pshirk(t+1))^2;                     %use equation 8
        pshirkadj(t+1)=min([1 pshirk(t+1)+lambda*(rep_exp_emp(t)-rep_act_emp(t))]);    %use equation 9
        
        
    else % ignore          
        if strcmp(button,'work')
            work(t)=1; 
            d_text=(upper('    no inspection.'));
        else
            work(t)=0; 
            d_text=upper('    no inspection, you got lucky.');
        end
        
        rep_act_emp(t)=rep_act_emp(max([1,t-1]));
        pshirk(t+1)=pshirk(t);
        rep_exp_emp(t+1)=rep_exp_emp(t);
        
        if previnspect==inspect(t)
            pshirkadj(t+1)=min([1 pshirkadj(t)+bonus]);
        else
            pshirkadj(t+1)=pshirkadj(t);
        end        
    end
    empcash (t+1)=empcash (t)+empgain (~work(t)+1,~inspect(t)+1);
    corpcash(t+1)=corpcash(t)+corpgain(~work(t)+1,~inspect(t)+1);    
    result(~work(t)+1,~inspect(t)+1)=result(~work(t)+1,~inspect(t)+1)+1;
    %fprintf('%s :$%0.2f\n',d_text,empgain(inspect(t)+1,~work(t)+1))
    fprintf('%s :$%0.2f\n',d_text,empgain(~work(t)+1,~inspect(t)+1))
    %empgain(:,1)
    % employee always knows if corp inspected
    if previnspect==inspect(t)
        rep_cnt_corp(mod(t,20)+1)=1;%update rep_cnt_emp if choice was repeated
    else
        rep_cnt_corp(mod(t,20)+1)=0;%update rep_cnt_emp if choice was repeated
    end        
    rep_act_corp(t)=sum(rep_cnt_corp)/min([t, repwindow]); %this trials actual repetition score;
    
    pinspect(t+1)=pinspect(t)+alpha*(inspect(t)-pinspect(t));                  %use equation 7           
    if pinspect(t+1)>1 | pinspect(t+1)<0
        pinspect(t+1)=round(pinspect(t+1)); % must be between 0 and 1
    end
    rep_exp_corp(t+1)=pinspect(t+1)^2+(1-pinspect(t+1))^2;                     %use equation 8 this makes no sense to me.
    pinspectadj(t+1)=min([1 pinspect(t+1)+lambda*(rep_exp_corp(t)-rep_act_corp(t))]);    %use equation 9
    
    
    
    
    
    %     SDinspect(t+1)=(1-pshirkadj(t+1))*corpgain(1,1) + pshirkadj(t+1)*corpgain(2,1);%inspect
    %     SDignore (t+1)=(1-pshirkadj(t+1))*corpgain(1,2) + pshirkadj(t+1)*corpgain(2,2);%ignore
    
    % +(.01-min(corpgain(:))) forces the min score to be .01 as i don't want to divied by zero  
    %                  work                           shirk
    SDinspect(t+1)=((1-pshirkadj(t+1))*corpgain(1,1) + pshirkadj(t+1)*corpgain(2,1))+(.01-min(corpgain(:)));%inspect
    SDignore (t+1)=((1-pshirkadj(t+1))*corpgain(1,2) + pshirkadj(t+1)*corpgain(2,2))+(.01-min(corpgain(:)));%ignore
    SDratio_corp(t+1)=(SDinspect(t+1)-SDignore(t+1))/(SDinspect(t+1)+SDignore(t+1));                      
    %                  inspect                           ignore
    SDwork (t+1)=(pinspectadj(t+1)*empgain(1,1) + (1-pinspectadj(t+1))*empgain(1,2))+(.01-min(empgain(:)));%inspect
    SDshirk(t+1)=(pinspectadj(t+1)*empgain(2,1) + (1-pinspectadj(t+1))*empgain(2,2))+(.01-min(empgain(:)));%ignore
    SDratio_emp(t+1)=(SDwork(t+1)-SDshirk(t+1))/(SDwork(t+1)+SDshirk(t+1));
    
    
    try
        % prob_inspect3(t+1)=1/(1+exp(-10*SDratio(t+1)+5)); % hers
        %prob_inspect(t+1)=decisionlookuptable(decisionlookuptable(:,1)==round(SDratio_corp(t+1)*100),2)/100; % mikes
        %prob_work(t+1)   =decisionlookuptable(decisionlookuptable(:,1)==round(SDratio_emp (t+1)*100),2)/100; % mikes        
        prob_inspect(t+1)=-1/(1+exp(15*SDratio_corp(t+1)))+1; % mine
        prob_work(t+1)   =-1/(1+exp(15*SDratio_emp(t+1)))+1; % mine
    catch
        error('duhhhh, this is for debugging')  
    end
    previnspect=inspect(t);
    prevwork=work(t);
    drawnow  
    
    runningwork(t)=mean(work(max([1,t-10]):t));
    runninginspect(t)=mean(inspect(max([1,t-10]):t));
    
end


fig(4);clf;
subplot(2,2,1);hold on
[cnt val ]=hist(prob_work,0:.05:1);
bar((val),cnt/max(cnt) ,1)
[cnt1 val1 ]=hist(prob_work,0:.001:1);
plot(val1,cumsum(cnt1)/sum(cnt),'r')
axis([0 1 0 1])
hline(.5);
vline(.5);

subplot(2,2,2);hold on
[cnt val ]=hist(prob_inspect,0:.05:1);
bar((val),cnt/max(cnt) ,1)
[cnt1 val1 ]=hist(prob_inspect,0:.001:1);
plot(val1,cumsum(cnt1)/sum(cnt),'r')
axis([0 1 0 1])
hline(.5);
vline(.5);

subplot(2,2,3);cla;hold on
plot([-1:.01:1],-1./(1+exp( 5*[-1:.01:1]))+1,'r')
plot([-1:.01:1],-1./(1+exp(10*[-1:.01:1]))+1,'k')
plot([-1:.01:1],-1./(1+exp(15*[-1:.01:1]))+1,'b')
plot([-1:.01:1],decisionlookuptable(1:1:201,2)/100,'c')
fred=  -1./(1+exp(5*[-1 SDratio_emp]))+1;
plot([-1 SDratio_emp],fred,'.r')
fred=  -1./(1+exp(10*[-1 SDratio_emp]))+1;
plot([-1 SDratio_emp],fred,'.k')
fred=  -1./(1+exp(15*[-1 SDratio_emp]))+1;
plot([-1 SDratio_emp],fred,'.b')
fred=decisionlookuptable(round((SDratio_emp+1)*100),2)/100;
plot(SDratio_emp,fred,'.c')
plot(SDratio_emp,prob_work,'+g')
hline(.5);vline(0);
legend('5*SDratio-emp','10*SDratio-emp','15*SDratio-emp','decisionlookuptable',2)

subplot(2,2,4);cla;hold on
plot([-1:.01:1],-1./(1+exp( 5*[-1:.01:1]))+1,'r')
plot([-1:.01:1],-1./(1+exp(10*[-1:.01:1]))+1,'k')
plot([-1:.01:1],-1./(1+exp(15*[-1:.01:1]))+1,'b')
plot([-1:.01:1],decisionlookuptable(1:1:201,2)/100,'c')
fred=  -1./(1+exp(5*[-1 SDratio_corp]))+1;
plot([-1 SDratio_corp],fred,'.r')
fred=  -1./(1+exp(10*[-1 SDratio_corp]))+1;
plot([-1 SDratio_corp],fred,'.k')
fred=  -1./(1+exp(15*[-1 SDratio_corp]))+1;
plot([-1 SDratio_corp],fred,'.b')
fred=decisionlookuptable(round((SDratio_corp+1)*100),2)/100;
plot(SDratio_corp,fred,'.c')
plot(SDratio_corp,prob_inspect,'+g')

hline(.5);vline(0);
legend('5*SDratio-corp','10*SDratio-corp','15*SDratio-corp','decisionlookuptable',2)


result
sum(inspect)
sum(work)
worked=sum(result(1,:))
shirked=sum(result(2,:))    
inspected=sum(result(:,1))
ignored=sum(result(:,2))

figure(10);clf;hold on
plot(runningwork,'b')
plot(runninginspect,'r');
hline(1-(coi/wage),'c');
hline(effort/wage,'m');
hline(mean(work),'b')
hline(.5,'--');
ylim([0 1])
legend('runningwork','runninginspect','worker''s equilibrium','corp''s equilibrium')



figure(11);clf;hold on
subplot(3,3, 1);cla; hold on;plot(pshirk,'b');plot(pshirkadj,'r');xlim([1 ntrials]);legend('pshirk','pshirkadj');ylim([0 1]);hline(.5);
subplot(3,3, 4);cla; hold on;plot(pinspect,'b');plot(pinspectadj,'r');xlim([1 ntrials]);legend('pinspect','pinspectadj');ylim([0 1]);hline(.5);
subplot(3,3, 2);cla; hold on;plot(rep_act_emp,'b');plot(rep_exp_emp,'r');xlim([1 ntrials]);legend('rep-act-emp','rep-exp-emp');ylim([0 1]);hline(.5);
subplot(3,3, 5);cla; hold on;plot(rep_act_corp,'b');plot(rep_exp_corp,'r');xlim([1 ntrials]);legend('rep-act-corp','rep-exp-corp');ylim([0 1]);hline(.5);
subplot(3,3, 3);cla; hold on;plot(SDratio_corp/2+.5,'b');plot(prob_inspect,'r');xlim([1 ntrials]);legend('SDratio-corp','prob-inspect');ylim([0 1]);hline(.5);
subplot(3,3, 6);cla; hold on;plot(SDratio_emp/2+.5,'b');plot(prob_work,'r');xlim([1 ntrials]);legend('SDratio-emp','prob-work');ylim([0 1]);hline(.5);
subplot(3,3, 7);cla; hold on;plot(SDinspect,'b');plot(SDignore,'r');xlim([1 ntrials]);legend('SDinspect','SDignore');
subplot(3,3, 8);cla; hold on;plot(SDwork,'b');plot(SDshirk,'r');xlim([1 ntrials]);legend('SDwork','SDshirk');
subplot(3,3, 9);cla; hold on;plot(empcash,'b');plot(corpcash,'r');xlim([1 ntrials]);legend('empcash','corpcash');



